<template>
  <!-- 门诊医生-处置 -->
  <div>
    <div class="flex justify-between items-center mb-2">
      <div class="flex items-center">
        <a-form :model="formState" class="flex items-center">
          <a-form-item label=" " :rules="[{ required: true, message: '请选择初步诊断' }]">
            <SelectTable
              v-model:value="formState.bcLczdZdmc"
              :disabled="formState.isCommit"
              type="诊断"
              class="mr-5 w-[300px]"
              @select="onSelectTable($event)"
            />
          </a-form-item>
          <a-form-item label="显示已作废医嘱"> <a-switch v-model:checked="showCancel" /> </a-form-item>
        </a-form>
      </div>
      <div>
        <a-button type="primary" class="mr-2" @click="saveSign()">签署</a-button>
        <a-button type="primary" ghost @click="templateModalOpen = true">套餐</a-button>
        <a-button type="primary" ghost class="ml-2" @click="batchModalOpen = true">批量处方</a-button>
        <a-dropdown class="ml-2" trigger="click">
          <a-button :icon="h(MenuOutlined)">打印</a-button>
          <template #overlay>
            <a-menu>
              <a-menu-item key="1" @click="onPrintAll()"> 全部</a-menu-item>
              <a-menu-item key="2" @click="onPrint('诊疗单申请单', 3, 0)"> 诊疗单</a-menu-item>
              <a-menu-item key="3" @click="onPrint('检查申请单', 0, 0)"> 检查单</a-menu-item>
              <a-menu-item key="4" @click="onPrint('材料申请单', 30, 0)"> 材料单</a-menu-item>
              <a-menu-item key="5" @click="onPrint('手术申请单', 6, 0)"> 手术单</a-menu-item>
              <a-menu-item key="6" @click="onPrintPlace(0)"> 处方单</a-menu-item>
              <a-sub-menu key="7" title="补打">
                <a-menu-item key="10" @click="onPrint('诊疗单申请单', 3)"> 诊疗单</a-menu-item>
                <a-menu-item key="11" @click="onPrint('检查申请单', 0)"> 检查单</a-menu-item>
                <a-menu-item key="12" @click="onPrint('材料申请单', 30)"> 材料单</a-menu-item>
                <a-menu-item key="13" @click="onPrint('手术申请单', 6)"> 手术单</a-menu-item>
                <a-menu-item key="14" @click="onPrintPlace('')"> 处方单</a-menu-item>
              </a-sub-menu>
            </a-menu>
          </template>
        </a-dropdown>
        <!-- <a-button class="ml-2" @click="onPrint('诊疗单申请单', 3)"> 诊疗单</a-button>
        <a-button class="ml-2" @click="onPrint('检查申请单', 0)"> 检查单</a-button>
        <a-button class="ml-2" @click="onPrint('材料申请单', 30)"> 材料单</a-button>
        <a-button class="ml-2" @click="onPrint('手术申请单', 6)"> 手术单</a-button>
        <a-button class="ml-2" @click="onPrintPlace">处方单</a-button> -->
      </div>
    </div>
    <BaseTable
      key="cfbh"
      max-fill
      :loading="loading"
      :data-source="dataSource"
      :scroll="{ x: 2400 }"
      column-code="000269"
      :extra-height="64"
      :pagination="false"
      :expanded-row-keys="expandedRowKeys"
      :row-class-name="getRowClass"
    >
      <template #bodyCell="{ column, index, record }">
        <template v-if="column.dataIndex === 'link'">
          <div class="table-link"></div>
        </template>
        <template v-if="column.dataIndex === 'yzzt'">
          <a-tag v-if="record.yzzt === 0" color="blue">新开立</a-tag>
          <a-tag v-if="record.yzzt === 1" color="green">已签署</a-tag>
          <a-tag v-if="record.yzzt === 2" color="red">已作废</a-tag>
        </template>
        <template v-if="column.dataIndex === 'mc'">
          <EditCell title="名称" :disabled="record.yzzt === 1">
            <SelectMedicine
              v-model:value="record.sfxm"
              :insure-status="record?.insureStatus"
              type="门诊医嘱项目"
              :auto-focus="record.isNew && index > 0 && !record.isSuit"
              @select="onSelect($event, record, index)"
            />
          </EditCell>
        </template>
        <template v-if="column.dataIndex === 'cfbh'">
          <template v-if="record.xmlb === 2 || record.xmlb === 4">
            <template v-if="record.stateCode">
              <EditCell title="处方号">
                <a-input ref="inputRef" v-model:value="record.cfbh" v-input-selection v-input:int placeholder="请输入" @blur="editPrescription(record)" />
              </EditCell>
            </template>
            <template v-else>
              {{ record?.cfbh }}
            </template>
          </template>
          <template v-else-if="record.isNew">{{ record?.cfbh }}</template>
          <template v-else>-</template>
        </template>
        <template v-if="column.dataIndex === 'yf'">
          <template v-if="record.xmlb === 2 || record.xmlb === 4">
            <EditCell title="给药途径" :disabled="record?.isChild">
              <SelectTable
                v-model:value="record.yf.fyff"
                :auto-focus="record.isNew && focusCell === record.key + '用法'"
                :table-width="360"
                type="用法"
                @select="onSelectWays($event, record)"
              />
            </EditCell>
          </template>
          <template v-else>-</template>
        </template>
        <template v-if="column.dataIndex === 'pl'">
          <template v-if="record.xmlb === 2 || record.xmlb === 4">
            <EditCell title="频次" :disabled="record.isChild">
              <SelectTable
                v-model:value="record.pl.pl"
                :auto-focus="record.isNew && focusCell === record.key + '频率'"
                :table-width="360"
                type="频率"
                @select="onSelectFrequency($event, record)"
              />
            </EditCell>
          </template>
          <template v-else>-</template>
        </template>
        <template v-if="column.dataIndex === 'jlsl'">
          <template v-if="record.xmlb === 2 || record.xmlb === 4">
            <EditCell :title="'剂量' + record.key">
              <BaseInput
                v-model:value="record.jlsl"
                v-input:float.3
                v-input-selection
                :auto-focus="record.isNew && focusCell === record.key + '剂量'"
                placeholder="请输入"
                :suffix="record?.sfxm.jldw"
                @keydown.enter="focusCell = record.key + (record.isChild ? '数量' : '天数')"
                @blur="onCalc(record)"
              />
            </EditCell>
          </template>
          <template v-else>-</template>
        </template>
        <template v-if="column.dataIndex === 'cfts'">
          <template v-if="record.xmlb === 2 || record.xmlb === 4">
            <EditCell title="天数" :disabled="record.isChild">
              <BaseInput
                v-model:value="record.cfts"
                v-input:float.3
                v-input-selection
                :auto-focus="record.isNew && focusCell === record.key + '天数'"
                suffix="天"
                placeholder="请输入"
                @keydown.enter="focusCell = record.key + '数量'"
                @blur="onCalc(record)"
              />
            </EditCell>
          </template>
          <template v-else>-</template>
        </template>
        <template v-if="column.dataIndex === 'sl'">
          <EditCell title="数量">
            <BaseInput
              v-model:value="record.sl"
              v-input:float.3
              v-input-selection
              :auto-focus="record.isNew && focusCell === record.key + '数量'"
              :suffix="record.sfxm?.dw"
              placeholder="请输入"
              @keydown.enter="saveAndAdd(record)"
              @blur="editRow(record)"
            />
          </EditCell>
        </template>
        <template v-if="column.dataIndex === 'yssm'">
          <EditCell title="医生说明">
            <a-input v-model:value="record.yssm" v-input-selection placeholder="请输入" @blur="editRow(record)" />
          </EditCell>
        </template>
        <template v-if="column.dataIndex === 'orderType'">
          {{ record.orderType === 2 ? '套餐' : '单项' }}
        </template>
        <template v-if="column.dataIndex === 'jfzt'">
          <a-tag v-if="record.jfzt === 0" color="blue">未收费</a-tag>
          <a-tag v-if="record.jfzt === 1" color="green">已收费</a-tag>
        </template>
        <template v-if="column.dataIndex === 'zxzt'">
          <a-tag v-if="record.zxzt === 0" color="blue">未执行</a-tag>
          <a-tag v-if="record.zxzt === 1" color="green">已执行</a-tag>
        </template>
        <template v-else-if="column.dataIndex === 'action'">
          <template v-if="record.xmlb === 2 || record.xmlb === 4">
            <a-button v-if="!record.isChild && record.orderType !== 2" :disabled="record.zxzt === 1" type="link" size="small" @click="addChildRow(record)">
              子医嘱
            </a-button>
          </template>
          <BaseButton v-if="record.yzzt === 1 && record.jfzt === 0" danger type="text" size="small" confirm-text="撤销签署?" @click="saveSign(record.id)">
            撤销
          </BaseButton>
          <BaseButton v-if="!record.isChild" confirm-text="确认作废？" type="link" size="small" :disabled="record.zxzt === 1" danger @click="onDelete(record)">
            作废
          </BaseButton>
          <BaseButton v-if="record.isChild" danger type="text" size="small" confirm-text="作废子医嘱?" @click="onDeleteChild(record)"> 作废子医嘱 </BaseButton>
          <a-button v-if="record?.insureStatus === 1" size="small" danger type="text" @click="onClickFunded(record, 2)">强制自费</a-button>
          <BaseButton v-if="record?.insureStatus === 2" confirm-text="撤销自费？" danger size="small" type="text" @click="onClickFunded(record, 1)">
            撤销自费
          </BaseButton>
          <!-- <a-button type="link" size="small" @click="onPrint(record)"> 打印 </a-button> -->
          <a-button v-if="(record?.xmlb === 2 || record?.xmlb === 4) && !isHaveNewRow" type="link" size="small" @click="onClickCode(record)">
            修改处方号
          </a-button>
        </template>
      </template>
      <template #footer>
        <div class="sticky bottom-0 flex justify-between pl-20 items-center">
          <div class="text-center flex-1">
            <a-button type="primary" class="mr-2" ghost :icon="h(PlusOutlined)" @click="addRow()"> 新增一行 </a-button>
            <a-button type="primary" :icon="h(SaveOutlined)" :disabled="selectDiagnosis ? !selectDiagnosis : !isHaveNewRow" @click="saveNewRows()">
              保存
            </a-button>
          </div>
        </div>
      </template>
    </BaseTable>
    <TemplateModal v-model:open="templateModalOpen" @success="onAddTemplate" />
    <BatchModal v-model:open="batchModalOpen" :data-source="dataSource" @success="getData" />
  </div>
</template>
<script setup>
import { ref, computed, watchEffect, h } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined, SaveOutlined, MenuOutlined } from '@ant-design/icons-vue'
import { intersection, maxBy } from 'lodash-es'
import BaseTable from '@/components/BaseTable'
import BaseButton from '@/components/BaseButton'
import EditCell from '@/components/EditCell'
import { post } from '@/utils/request'
import cofirmModal from '@/utils/confirm'
import useUserStore from '@/store/user'
import useStore from '../store'
import TemplateModal from './TemplateModal'
import BatchModal from './BatchModal'

// const open = ref(false)

const { empId } = useUserStore()

const props = defineProps({
  activeKey: {
    type: String,
    default: ''
  }
})
const store = useStore()

const focusCell = ref(null)
const inputRef = ref(null)
const templateModalOpen = ref(false)
const batchModalOpen = ref(false)
const loading = ref(false)
const isEmpty = ref(true)
const showCancel = ref(false)
const selectDiagnosis = ref(false)
const formState = ref({})
const dataSource = ref([])
const tableListId = ref([])
const expandedRowKeys = ref([])
const medicationData = ref([])
const signState = ref()
const mrmCode = ref()
// const defaultRow = { isNew: true, cfbh: 1, yzzt: 0 }

//获取门诊患者信息
const getOutpatientInfo = async () => {
  const { data, code } = await post('/outp/mzys/getOutpRecordInfo', { mzjlbh: store.currentPatient.jzbh })
  if (code === 0) {
    formState.value = data
  }
}

const onSelectTable = (select) => {
  formState.value.bcLczdZddm = select.zddm
  formState.value.bcLczdZdmc = select.zdmc
  selectDiagnosis.value = true
}

const onClickCode = (row) => {
  row.stateCode = true
  nextTick(() => {
    const inputComponent = inputRef.value
    if (inputComponent && inputComponent.$el) {
      // 将焦点设置到输入框上
      inputComponent.$el.focus()
    }
  })
}
const editPrescription = async (record) => {
  // cfbh:record?.cfbh,yzid:record.id
  const res = await post('/outp/mzys/upPrescriptionNumber', { cfbh: record?.cfbh, yzid: record.id })
  if (res.code !== 0) {
    getData()
    return message.error(res.msg || '修改失败')
  }
  getData()

  message.success(res.msg || '修改成功')
}

//创建新行
const generateRow = (isChild = false) => {
  return {
    id: '',
    yzzt: 0,
    yf: {},
    pl: {},
    key: `row-key-${Math.random().toString().slice(2)}`,
    ...(!isChild && { children: [] }),
    isChild,
    isNew: true
  }
}

const isHaveNewRow = computed(() => {
  return dataSource.value.some((item) => item.isNew)
})
//删除空行
const onDeleteEmptyRow = () => {
  dataSource.value = dataSource.value.filter((item) => item.sfxm?.mc)
}
const saveNewRows = async (addNew) => {
  onDeleteEmptyRow()
  dataSource.value.forEach((item) => {
    if (!item.sfxm || !item.sl) {
      message.destroy()
      isEmpty.value = false
      return message.error('请填写完整信息')
    } else {
      isEmpty.value = true
    }
  })
  isEmpty.value && (await fetchSave(addNew))
  onSaveMedical()
  // const newRows = dataSource.value.filter((item) => item.isNew)
  // newRows.forEach((item) => {
  //   fetchSave(item, addNew)
  // })
}
const getMedical = async () => {
  const res = await post('/common/masterData/getByYsbhDepartment', { empId })
  if (res.code !== 0) return message.error(res.msg)
  mrmCode.value = res.data && res.data.blmb
}
const onSaveMedical = async () => {
  const res = await post('outp/mzys/doSavePatientEMR', {
    ...formState.value,
    brId: store.currentPatient.brId,
    jzbh: store.currentPatient.jzbh,
    mrmCode: mrmCode.value,
    qtzdxx: '',
    isCxtj: undefined,
    isCommit: undefined
  })
  if (res.code !== 0) return message.error(res.msg)
}

const editRow = (row) => {
  if (row.yzzt === 1) {
    message.error('已签署不可修改')
    getData()
  } else {
    !row.isNew && saveNewRows()
  }
}
const fetchSave = async (addNew = false) => {
  // 判断有没有选择诊断
  if (!formState.value.bcLczdZdmc) {
    return message.error('请选择诊断')
  }
  // 去除已作废的
  const newList = dataSource.value.filter((i) => {
    return i.yzzt !== 2
  })
  const newRows = newList.map((row) => {
    return {
      jzbh: store.currentPatient.jzbh, //编号
      ...row
    }
  })
  const { code, msg } = await post('/outp/mzys/doSaveOutpClinicalOrderInfoList', newRows)
  if (code !== 0) return message.error(msg || '操作失败')
  message.success('保存成功')
  await getData(addNew)
}

// 签署
const saveSign = async (id = '') => {
  await fetchSave()
  if (!tableListId.value.length) {
    return message.error('不能为空')
  }
  id ? (signState.value = 0) : (signState.value = 1)
  const { code, msg } = await post('/outp/mzys/signedDoctor', {
    yzid: id ? [id] : tableListId.value,
    yzzt: signState.value
  })
  if (code !== 0) return message.error(msg)
  message.destroy()
  message.success('签署成功')
  getData()
}

//获取数据
const getData = async (addNew) => {
  loading.value = true
  const { data, code } = await post('/outp/mzys/getPatientPrescriptionList', {
    jzbh: store.currentPatient.jzbh, //就诊编号
    czsfck: showCancel.value ? 1 : 0
  })
  loading.value = false
  if (code !== 0) return
  if (data.length > 0) {
    dataSource.value = data.map((item) => {
      return { ...item, key: item.id, stateCode: false }
    })
    expandedRowKeys.value = data.map((item) => item.id)
    tableListId.value = []
    dataSource.value.forEach((i) => {
      i.id && tableListId.value.push(i.id)
      if (i.children.length > 0) {
        i.children.forEach((j) => {
          j.isChild = true
          j.stateCode = false
          tableListId.value.push(j.id)
        })
      }
    })
    addNew && addRow()
  } else {
    dataSource.value = [{ key: 'row-0', ...generateRow() }]
  }
}

watchEffect(() => store.currentPatient.jzbh && getData())

const onAddTemplate = (list) => {
  //判断处方中是否有重复项目
  const currentTableYPBHS = dataSource.value.map((item) => item.sfxm?.bh)
  const templateYPBHS = list.map((item) => {
    item.zje = item.sl * item.dj
    item.yzzt = 0
    return item.bh
  })
  const repeatIds = intersection(currentTableYPBHS, templateYPBHS)
  if (repeatIds.length > 0) {
    const itemName = dataSource.value.find((item) => item.sfxm?.bh === repeatIds[0]).mc
    return message.error(`已有项目【${itemName}】，请勿重复添加`)
  }
  onDeleteEmptyRow()
  const maxData = maxBy(dataSource.value, 'cfbh')
  const packageList = list.map((item) => {
    //获取之前最大的处方号
    if (maxData?.cfbh && Number(maxData?.cfbh)) {
      item.cfbh = Number(maxData?.cfbh) + 1
    } else {
      item.cfbh = 1
    }
    return item
  })
  templateModalOpen.value = false
  dataSource.value = [...dataSource.value, ...packageList]
  dataSource.value.forEach((i) => {
    if (i.xmlb !== 2 && i.xmlb !== 4) {
      i.cfbh = ''
    }
  })
}
const getRowClass = (record) => {
  const className = {
    'table-row-suit': record.isSuit,
    'table-row-new': record.isNew,
    'table-row-readonly': record.zxzt === 1,
    'table-row-disabled': record.yzzt === 2
  }
  return Object.keys(className)
    .filter((key) => className[key])
    .join(' ')
}
const onSelect = (selected, record) => {
  record.sfxm = selected
  if (selected.xmlb === 2 || selected.xmlb === 4) {
    record.cfbh = record.cfbh || getCfbh()
  } else {
    record.cfbh = ''
  }
  // record.jlsl = 1
  // record.cfts = record.cfts || 1
  record.sl = 1
  record.xmlb = selected.xmlb
  if (record.xmlb === 2 || record.xmlb === 4) {
    focusCell.value = `${record.key}${record.isChild ? '剂量' : '用法'}`
  } else {
    focusCell.value = `${record.key}数量`
  }
  editRow(record)
  getSelectUsage(selected, record)
}

// 获取用法和频次
const getSelectUsage = async (medicine, row) => {
  const { code, data, msg } = await post('/common/masterData/getDictDrugDefaultUsage', { bh: medicine.bh })
  if (code !== 0) return message.error(msg)
  medicationData.value = data
  data[0]?.fyff && (data[0].fyff.isSelectDrug = true)
  data[0]?.pl && (data[0].pl.isSelectDrug = true)
  data[0]?.fyff && onSelectWays(data[0].fyff, row)
  data[0]?.pl && onSelectFrequency(data[0].pl, row)
}

//选用法
const onSelectWays = (selected, row) => {
  if (medicationData.value.length > 0) {
    const isNull = medicationData.value.some((i) => i.fyff)
    const selectUsage = medicationData.value.some((i) => i.fyff?.fyffid === selected?.fyffid)
    isNull && !selectUsage && message.error('该给药途径不在设置范围内，请注意')
  }
  row.yf = selected
  row?.children.length && row.children.forEach((item) => (item.yf = selected))
  !selected.isSelectDrug && (focusCell.value = row.key + '频率')
  editRow(row)
}
//选频率
const onSelectFrequency = (selected, row) => {
  if (medicationData.value.length > 0) {
    const isNull = medicationData.value.some((i) => i.pl)
    const selectUsage = medicationData.value.some((i) => i.pl?.plid === selected?.plid)
    isNull && !selectUsage && message.error('该给药频次不在设置范围内，请注意')
  }
  row.pl = selected
  row?.children.length && row.children.forEach((item) => (item.pl = selected))
  !selected.isSelectDrug && (focusCell.value = row.key + '剂量')
  // row.yssm = `${row?.yssm || ''}  ${selected?.pltime || ''}`
  onCalc(row)
}

// 自费
const onClickFunded = async (row, state) => {
  const { code, msg } = await post('/outp/mzys/doCompulsorySelfpaymentInfo', {
    insureStatus: state,
    yzbh: row.id
  })
  if (code !== 0) return message.error(msg)
  message.success(msg)
  getData()
}
const onDelete = async (row) => {
  if (row.isNew) {
    if (row.isSuit) {
      dataSource.value = dataSource.value.filter((item) => item.tcid !== row.tcid)
    } else {
      const index = dataSource.value.findIndex((item) => item.key === row.key)
      dataSource.value.splice(index, 1)
    }
    message.success('删除成功')
  } else {
    const { code } = await post('/outp/mzys/doDelOutpClinicalOrderInfo', { yzbh: row.id })
    if (code !== 0) return message.error('删除失败')
    message.success('删除成功')
    getData()
  }
}

// 作废子医嘱
const onDeleteChild = async (row) => {
  if (row.isNew) {
    const fData = dataSource.value.find((item) => item.key === row.fkey)
    const index = fData.children.findIndex((item) => item.key === row.key)
    fData.children.splice(index, 1)
  } else {
    onDelete(row)
  }
}
const saveAndAdd = async (row) => {
  await fetchSave(row)
  addRow()
}

const getCfbh = () => {
  const maxData = dataSource.value.reduce(function (prev, current) {
    return +prev.cfbh > +current.cfbh ? prev : current
  })
  const newData = dataSource.value.filter((item) => item.yzzt === 0 && item.orderType !== 2 && item.cfbh !== '0')[0]
  if (newData?.cfbh) {
    return newData.cfbh
  } else if (maxData?.cfbh) {
    return Number(maxData.cfbh) + 1
  } else {
    return 1
  }
}

//添加行
const addRow = async () => {
  onDeleteEmptyRow()
  const newRow = generateRow()
  const cfbh = getCfbh()
  const cfbhCount = dataSource.value.filter((i) => i.cfbh === cfbh).length
  if (cfbhCount === 5) {
    const isConfirm = await cofirmModal({ title: '提示', content: '单张处方不建议超过5个药，是否继续添加？' })
    if (!isConfirm) return
  }
  dataSource.value.push({ ...newRow, stateCode: false, cfbh })
  focusCell.value = newRow.key + '药品名称'
}
//添加子医嘱
const addChildRow = async (row) => {
  onDeleteEmptyRow()
  const cfbhCount = dataSource.value.filter((i) => i.cfbh === row.cfbh).length
  if (cfbhCount === 5) {
    const isConfirm = await cofirmModal({ title: '提示', content: '单张处方不建议超过5个药，是否继续添加？' })
    if (!isConfirm) return
  }
  if (!row.sfxm || !row.yf || !row.pl || !row.sl || !row.cfts) return message.error('请先填写主医嘱')
  const extendParams = { yf: row.yf, pl: row.pl, cfts: row.cfts }
  const newRow = generateRow(true)
  const addRow = { fkey: row.key, cfbh: row.cfbh, ...newRow, ...extendParams }
  row.isNew = true
  row.children.push(addRow)
  focusCell.value = addRow.key + '药品名称'
}

// 手术申请单 、 诊疗单申请单、 材料申请单 、 检查申请单
const onPrint = (type, category, jfzt) => {
  const filterData = dataSource.value.filter((i) => i.xmlb === category)
  const countArray = getField(filterData, 'dybh')
  countArray.forEach(async (i) => {
    const { code, msg, data } = await post('/outp/outPrint/printrptDJ_TY', {
      jzbh: store.currentPatient.jzbh,
      djlx: type,
      dybh: i?.dybh,
      jfzt: jfzt ?? undefined
    })
    if (code !== 0) return message.error(msg)
    window.openExe?.rpt(data) //调用winform打印
  })
}

// 打印全部
const onPrintAll = () => {
  const printArr = [
    {
      type: '诊疗单申请单',
      category: 3,
      jfzt: 0
    },
    {
      type: '检查申请单',
      category: 0,
      jfzt: 0
    },
    {
      type: '材料申请单',
      category: 30,
      jfzt: 0
    },
    {
      type: '手术申请单',
      category: 6,
      jfzt: 0
    }
  ]
  printArr.forEach((i) => onPrint(i.type, i.category, i.jfzt))
  onPrintPlace(0)
}

const getField = (array, field) => {
  const seen = {}
  return array.filter((item) => {
    const key = item[field]
    if (seen[key]) {
      // 已经出现过，不保留
      return false
    } else {
      // 记录下已经出现的key
      seen[key] = true
      return true
    }
  })
}

// 处方
const onPrintPlace = (jfzt) => {
  const filterData = dataSource.value.filter((i) => i.xmlb === 2 || i.xmlb === 4)
  const countArray = getField(filterData, 'cfbh')
  countArray.forEach(async (i) => {
    const { code, msg, data } = await post('/outp/outPrint/getMedicinePrescriptionOrdersPrint', {
      jzbh: store.currentPatient.jzbh,
      cfbh: i?.cfbh,
      jfzt: jfzt === 0 ? jfzt : undefined
    })
    if (code !== 0) return message.error(msg)
    window.openExe?.rpt(data) //调用winform打印
  })
}
const onCalc = async (row) => {
  if (!row.cfts || !row.jlsl || !row.pl?.pl || !row.sfxm) return
  const { data, code } = await post('/outp/mzys/calculateTheTotal', {
    cfts: row.cfts,
    jlsl: row.jlsl,
    pl: row.pl,
    sfxm: row.sfxm
  })
  if (code !== 0) return message.error('计算失败')
  row.sl = data
  editRow(row)
}

// const getTotal = async () => {
//   const { data, code } = await post('/outp/outpClinicalOrder/getOutpClinicalOrderAmount', {
//     jzbh: store.currentPatient.jzbh, //就诊编号
//     iscz: ''
//   })
//   if (code !== 0) return
//   totalPrice.value = data?.amount || '0.00'
// }

watch(
  () => props.activeKey,
  (val) => {
    if (val === '2') {
      getOutpatientInfo()
    }
  },
  {
    immediate: true
  }
)
watch(
  () => store.currentPatient.jzbh,
  () => {
    getOutpatientInfo()
  }
)
onMounted(() => {
  getMedical()
})
</script>
<style lang="less" scoped>
.ant-form {
  :deep(.ant-form-item) {
    margin-bottom: 0;
    .ant-form-item-required {
      height: 0;
    }
    .ant-form-item-required::before {
      margin-inline-end: 0 !important;
    }
  }
}

:deep(.ant-table-row-expand-icon) {
  display: none;
}
:deep(.ant-dropdown-menu-item-active) {
  color: var(--primary-color) !important;
}
</style>
